package com.accounting;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.Alert;
import com.accounting.ui.LoginView;
import com.accounting.ui.MainView;
import com.accounting.db.DatabaseManager;
import com.accounting.util.ConfigManager;

public class Main extends Application {
    private Stage primaryStage;
    private Scene loginScene;
    private Scene mainScene;

    @Override
    public void start(Stage primaryStage) {
        this.primaryStage = primaryStage;
        
        try {
            // 初始化数据库
            DatabaseManager.initDatabase();
            DatabaseManager.initializeCategories();
            
            // 创建登录场景
            LoginView loginView = new LoginView();
            loginScene = new Scene(loginView.getView(), 400, 300);
            
            // 应用主题
            String theme = ConfigManager.getTheme();
            loginScene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
            if ("dark".equals(theme)) {
                loginScene.getStylesheets().add(getClass().getResource("/css/themes/dark-theme.css").toExternalForm());
            }

            // 设置登录成功后的动作
            loginView.setOnLogin(() -> {
                if (validateLogin(loginView.getUsername(), loginView.getPassword())) {
                    // 创建主场景，传入用户名
                    MainView mainView = new MainView(loginView.getUsername());
                    mainScene = new Scene(mainView.getView(), 1000, 700);
                    mainScene.getStylesheets().add(getClass().getResource("/css/style.css").toExternalForm());
                    showMainView();
                }
            });

            // 显示登录界面
            primaryStage.setTitle("登录 - 家庭记账系统");
            primaryStage.setScene(loginScene);
            primaryStage.show();
        } catch (Exception e) {
            e.printStackTrace();
            showError("错误", "初始化系统失败：" + e.getMessage());
        }
    }

    private boolean validateLogin(String username, String password) {
        return DatabaseManager.validateUser(username, password);
    }

    private void showMainView() {
        primaryStage.setTitle("家庭记账系统");
        primaryStage.setScene(mainScene);
        primaryStage.setMaximized(true);
    }

    private void showError(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
} 